package com.lzx.iteam;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.*;
import android.widget.*;
import com.lzx.iteam.adapter.CloudContactAdapter;
import com.lzx.iteam.bean.CloudContact;
import com.lzx.iteam.bean.PhoneNumItem;
import com.lzx.iteam.net.*;
import com.lzx.iteam.provider.CloudDBOperation;
import com.lzx.iteam.util.*;
import io.rong.imageloader.core.ImageLoader;
import com.umeng.analytics.MobclickAgent;
import io.rong.imkit.RongIM;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Megan on 15/9/10.
 */
public class CloudContactDetailActivity extends Activity implements View.OnClickListener {
    public static final String ACTION_CLOUD_CONTACT = "com.lzx.iteam.ACTION_CLOUD_CONTACT";
    private ImageLoader mImageLoader;
    private ScrollView mSvCloudContact;
    private LinearLayout mMainLayout, mLlBack, mLlMore, mLlChatBtn, mLlNote,mLlHelp;
    private RelativeLayout mRlPersonNote;
    private RelativeLayout mRlSchedule;
    private TextView mTvSchedule;
    private TextView mTvContactName, mTvContactPhone, mTvContactPosition, mTvContactCompany, mTvContactEmail, mTvContactAddress, mTvContactNote;
    private ImageView mIvContactSex, mIvContactPhoto, mIvContactStatus;
    private ImageView mIvAuthIn, mIvAuthLook, mIvShare;
    private LinearLayout mLlAuthMore;
    private ImageView mIvTalkImage1, mIvTalkImage2, mIvTalkImage3, mIvTalkImage4;
    private LinearLayout mLlTalkImage;
    private RelativeLayout mRlTalkImage;
    private SendCardShakeListener mShaker;

    private int mCloudContactSex;
    private String mCalendarPurview;
    private String mCloudContactNote;
    private String mLimitPhone;
    private String mCloudContactName;
    private String mCloudImage = "";
    private String mCloudContactCompany;
    //    private String mCloudContactDepartment = "";//目前没这个字段了
    private String mCloudContactPosition;
    private String mCloudContactEmail;
    private StringBuilder mCloudAddress;
    private ArrayList<String> mCloudPhoneNumbers;

    private CloudDBOperation mCloudDBOperation;
    //团队人相关
    private String mCloudContactId;
    private String mCloudCurrentContactId;
    private String mCloudGroupId;
    private String mCloudGroupName;
    private String mUserId;
    private String mUserType;//-1:虚拟成员(对于团队模板来说); 0:未注册成员;1:普通成员;2:管理者;3:创建者
    private CloudContact cloudContact;

    private String myUid;

    private PreferenceUtil mPreferenceUtil;
    private AllDialogUtil mDialogUtil;
    private Dialog mDialog;
    private ShareUtil mShareUtil;
    private PopupWindow mMoreWindow;

    private int mAccess;//1.禁止, 0.开放(默认开放)--是否允许进入我的个人空间
    private int mShield;//1.禁止, 0.开放(默认开放)--是否屏蔽此人动态

    private final int REMOVE_CLOUD_CONTACT = 10000;
    private final int GET_CLOUD_CONTACT = 10001;
    private final int MSG_AUTH_DETAIL = 10003;
    private final int MSG_AUTH_ACCESS = 10004;
    private final int MSG_AUTH_SHIELD = 10005;
    private final int MSG_TALK_PREVIEW = 10006;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
//                case Constants.MSG_DATA_READY:
//                    mInfo = (ContactInfo) msg.obj;
//                    setLocalContactData(mInfo);
//                    break;
                case REMOVE_CLOUD_CONTACT:
                    mDialog.dismiss();
                    if (msg.arg1 == 0) {
                        new AsyncTask<Void, Void, Void>() {

                            @Override
                            protected Void doInBackground(Void... voids) {
                                mCloudDBOperation.deleteContactByPhone(myUid, mCloudPhoneNumbers.get(0));
                                return null;
                            }
                        }.execute();
                        setResult(Constants.ACTIVITY_RESULT_CLOUD_CONTACT_DELETE);
                        finish();
                        /*dialogUtil.titleMsgBtnStyle("提示", getString(R.string.remove_contact_success), getString(R.string.label_btn_ok));
                        dialogUtil.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {

                            @Override
                            public void onConfirmClick(Dialog lDialog) {
                                lDialog.dismiss();
                                setResult(Constants.ACTIVITY_RESULT_CLOUD_CONTACT_DELETE);
                                finish();
                            }

                            @Override
                            public void onCancelClick(Dialog lDialog) {
                            }
                        });*/

                    } else {

//                        dialogUtil.titleMsgBtnStyle("提示", getString(R.string.remove_contact_fail), getString(R.string.label_btn_ok));
                        mDialogUtil.titleMsgBtnStyle("提示", msg.obj.toString(), getString(R.string.label_btn_ok));
                        mDialogUtil.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {

                            @Override
                            public void onConfirmClick(Dialog lDialog) {
                                lDialog.dismiss();
                                finish();
                            }

                            @Override
                            public void onCancelClick(Dialog lDialog) {
                            }
                        });
                    }
                    break;
                case GET_CLOUD_CONTACT:
                    if (msg.arg1 == 0) {
                        if (msg.obj != null) {
                            cloudContact = (CloudContact) msg.obj;
                            setCloudContactData(cloudContact);
                        }
                        Log.i("cloudContact", cloudContact.toString());
                    }
                    break;

                case MSG_AUTH_DETAIL:
                    if (msg.arg1 == 0) {
                        Map<String, Integer> map = (Map<String, Integer>) msg.obj;
                        mAccess = map.get("access");
                        mShield = map.get("shield");
                        setAuthIcon();
                    }
                    break;
                case MSG_AUTH_ACCESS:
                    if (msg.arg1 == 0) {
                        Map<String, Integer> map = (Map<String, Integer>) msg.obj;
                        mAccess = map.get("set_type");
                        setAuthIcon();
                        LayoutInflater inflater = getLayoutInflater();
                        View layout = inflater.inflate(R.layout.operate_success_layout, null);
                        Toast toast = new Toast(getApplicationContext());
                        toast.setGravity(Gravity.CENTER, 0, 0);
                        toast.setDuration(Toast.LENGTH_LONG);
                        toast.setView(layout);
                        toast.show();
                    }
                    break;
                case MSG_AUTH_SHIELD:
                    if (msg.arg1 == 0) {
                        Map<String, Integer> map = (Map<String, Integer>) msg.obj;
                        mShield = map.get("set_type");
                        setAuthIcon();
                        getTalkPreView(CloudContactDetailActivity.this, mHandler.obtainMessage(MSG_TALK_PREVIEW));
                        LayoutInflater inflater = getLayoutInflater();
                        View layout = inflater.inflate(R.layout.operate_success_layout, null);
                        Toast toast = new Toast(getApplicationContext());
                        toast.setGravity(Gravity.CENTER, 0, 0);
                        toast.setDuration(Toast.LENGTH_LONG);
                        toast.setView(layout);
                        toast.show();

                    }
                    break;
                case MSG_TALK_PREVIEW:
                    if (msg.arg1 == 0) {
                        ArrayList<String> list = (ArrayList<String>) msg.obj;
                        if (list.size() > 0) {
                            mLlTalkImage.setVisibility(View.VISIBLE);
                            switch (list.size()) {
                                case 4:
                                    mImageLoader.displayImage(list.get(3), mIvTalkImage4, ImageLoaderInterface.optionEventImage);
                                case 3:
                                    mImageLoader.displayImage(list.get(2), mIvTalkImage3, ImageLoaderInterface.optionEventImage);
                                case 2:
                                    mImageLoader.displayImage(list.get(1), mIvTalkImage2, ImageLoaderInterface.optionEventImage);
                                case 1:
                                    mImageLoader.displayImage(list.get(0), mIvTalkImage1, ImageLoaderInterface.optionEventImage);
                                    break;

                            }

                        } else {
                            mLlTalkImage.setVisibility(View.GONE);
                        }
                    }

                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.cloud_contact_detail_layout);
        initViews();
        initProperty();
        parseCloudIntent();
        getCloudContact(CloudContactDetailActivity.this, mCloudContactId + "", mHandler.obtainMessage(GET_CLOUD_CONTACT));
        getAuthDetail(this, mHandler.obtainMessage(MSG_AUTH_DETAIL));
        if (!"0".equals(mUserId)) {
            getTalkPreView(this, mHandler.obtainMessage(MSG_TALK_PREVIEW));
        }
        SealAppContext.getInstance().pushActivity(this);

    }

    private void initViews() {
        mMainLayout = (LinearLayout) this.findViewById(R.id.cloud_contact_detail_main);
        mLlHelp = (LinearLayout) this.findViewById(R.id.cloud_contact_ll_help);
        mSvCloudContact = (ScrollView) this.findViewById(R.id.sv_contact_detail);
        mLlBack = (LinearLayout) this.findViewById(R.id.ll_cloud_contact_btn_back);
        mLlMore = (LinearLayout) this.findViewById(R.id.ll_cloud_contact_btn_more);
        mLlChatBtn = (LinearLayout) this.findViewById(R.id.ll_cloud_chat_btn);
        mLlNote = (LinearLayout) this.findViewById(R.id.ll_cloud_contact_detail_note);

        mRlPersonNote = (RelativeLayout) this.findViewById(R.id.rl_contact_detail_person_note);
        mTvSchedule = (TextView) this.findViewById(R.id.tv_contact_detail_schedule);
        mRlSchedule = (RelativeLayout) this.findViewById(R.id.rl_contact_detail_schedule);
        mTvContactName = (TextView) this.findViewById(R.id.cloud_contact_detail_name);
        mTvContactPhone = (TextView) this.findViewById(R.id.cloud_contact_detail_phone);
        mTvContactAddress = (TextView) this.findViewById(R.id.cloud_contact_detail_address);
        mTvContactEmail = (TextView) this.findViewById(R.id.cloud_contact_detail_email);
        mTvContactPosition = (TextView) this.findViewById(R.id.cloud_contact_detail_position);
        mTvContactCompany = (TextView) this.findViewById(R.id.cloud_contact_detail_company);
        mTvContactNote = (TextView) this.findViewById(R.id.cloud_contact_detail_note);
        mIvContactSex = (ImageView) this.findViewById(R.id.cloud_contact_detail_sex);
        mIvContactPhoto = (ImageView) this.findViewById(R.id.cloud_contact_photo);
        mIvContactStatus = (ImageView) this.findViewById(R.id.cloud_contact_status);

        mIvAuthIn = (ImageView) this.findViewById(R.id.cloud_contact_auth_in);
        mIvAuthLook = (ImageView) this.findViewById(R.id.cloud_contact_auth_look);
        mIvShare = (ImageView) this.findViewById(R.id.cloud_contact_share);
        mLlAuthMore = (LinearLayout) this.findViewById(R.id.cloud_contact_detail_btn);


        mIvTalkImage1 = (ImageView) this.findViewById(R.id.iv_contact_detail_talk_img1);
        mIvTalkImage2 = (ImageView) this.findViewById(R.id.iv_contact_detail_talk_img2);
        mIvTalkImage3 = (ImageView) this.findViewById(R.id.iv_contact_detail_talk_img3);
        mIvTalkImage4 = (ImageView) this.findViewById(R.id.iv_contact_detail_talk_img4);
        mLlTalkImage = (LinearLayout) this.findViewById(R.id.ll_contact_detail_talk_img);
        mRlTalkImage = (RelativeLayout) this.findViewById(R.id.rl_contact_detail_talk_img);

        mLlBack.setOnClickListener(this);
        mLlHelp.setOnClickListener(this);
        mLlMore.setOnClickListener(this);
        mLlChatBtn.setOnClickListener(this);
        mRlPersonNote.setOnClickListener(this);
        mIvContactPhoto.setOnClickListener(this);
        mIvShare.setOnClickListener(this);
        mRlTalkImage.setOnClickListener(this);
        mRlSchedule.setOnClickListener(this);
    }

    private void initProperty() {
        mCloudDBOperation = new CloudDBOperation(CloudContactDetailActivity.this);
        mPreferenceUtil = PreferenceUtil.getInstance(CloudContactDetailActivity.this);
        mDialogUtil = AllDialogUtil.getInstance(this);
        mDialog = mDialogUtil.waitDialog();
        mShareUtil = ShareUtil.getInstance(this);
        mUserType = mPreferenceUtil.getString("create_type", "1");
        mImageLoader = ImageLoader.getInstance();
        myUid = mPreferenceUtil.getString(PreferenceUtil.CLIENT_USEID, "－1");
    }

    /**
     * 解析云号码CloudContactAdapter onclick事件中Intent携带的云号码数据
     */
    private void parseCloudIntent() {
        Intent mIntent = getIntent();
        mCloudCurrentContactId = mIntent.getStringExtra("current_contact_id");
        mCloudContactId = mIntent.getStringExtra("contact_id");
        mCloudGroupId = mIntent.getStringExtra("group_id");
        mCloudGroupName = mIntent.getStringExtra("group_name");
        mUserId = mIntent.getStringExtra("user_id");

        if (mCloudGroupId != null && mCloudGroupId.equals("561")) {
//            mScrollView.setClickable(false);
            mLlMore.setClickable(false);
            mLlChatBtn.setClickable(false);
        }
        /*if (mPreferenceUtil.getString(PreferenceUtil.CLIENT_USEID, "－1").equals(mUserId)) {
            mLlMore.setVisibility(View.VISIBLE);
        }else{
            // TODO createType:  0:未注册  1: 普通成员  2: 管理员  3: 创建者
            if ("2".equals(mUserType) || "3".equals(mUserType)) {
                mLlMore.setVisibility(View.VISIBLE);
            }else{
                mLlMore.setVisibility(View.GONE);
            }
        }*/
        mLlMore.setOnClickListener(this);
        mLlAuthMore.setVisibility(View.VISIBLE);
        if ("2".equals(mUserType) || "3".equals(mUserType)) {
            mIvShare.setVisibility(View.VISIBLE);
        } else {
            mIvShare.setVisibility(View.GONE);
        }

    }

    /**
     * 设置云端数据
     *
     * @param cloudContact
     */
    private void setCloudContactData(CloudContact cloudContact) {

        mCalendarPurview = cloudContact.calendar_purview;
        mCloudContactSex = cloudContact.contact_sex;
        mCloudContactNote = cloudContact.contactRemarks;
        mLimitPhone = cloudContact.phone_purview;
        mCloudContactName = cloudContact.contactName;
        mCloudImage = cloudContact.contact_image;
        //JSONObject object = cloudContact.contact_card;
        String phone = cloudContact.contact_phone;

        // TODO 第二个号码又去掉了
        //String landline = cloudContact.contact_landline;
        mCloudPhoneNumbers = new ArrayList<String>();
        mCloudPhoneNumbers.add(phone);
        //mCloudPhoneNumbers.add(landline);

        // TODO 此处必须先判断得到数据里有没有公司或者职位的字段
        JSONObject object = null;
        try {
            object = new JSONObject(cloudContact.contact_card);
            if (object != null && object.has("organization")) {
                mCloudContactCompany = object.getString("organization");
            } else {
                mCloudContactCompany = "";
            }

            if (object.has("jobtitle")) {

                mCloudContactPosition = object.getString("jobtitle");
            } else {
                mCloudContactPosition = "";
            }
            if (object.has("demails")) {

                JSONObject emailObject = object.getJSONObject("demails");
                StringBuilder email = new StringBuilder();
                if (emailObject.has("_$!<Work>!$_")) {
                    email.append(emailObject.getString("_$!<Work>!$_"));
                }
                if (emailObject.has("_$!<Home>!$_")) {
                    email.append("  " + emailObject.getString("_$!<Home>!$_"));
                }
                mCloudContactEmail = email.toString();

            } else {
                mCloudContactEmail = "";
            }
/*部门字段目前没了
            if (object.has("department")) {
                mCloudContactDepartment = object.getString("department");
            } else {
                mCloudContactDepartment = "";
            }
*/

            // 解析地址信息，有两种情况，一种是按原手机通讯录上传格式，一种是后来设置的方式，只有_$!<Work>!$_字段
            mCloudAddress = new StringBuilder();
            if (object.has("daddresses")) {
                JSONObject address = object.getJSONObject("daddresses");
                JSONObject add = address.getJSONObject("_$!<Work>!$_");
                if (add.has("City")) {
                    mCloudAddress.append(add.getString("City"));
                }
                if (add.has("State")) {
                    mCloudAddress.append(add.getString("State"));
                }
                if (add.has("Street")) {
                    mCloudAddress.append(add.getString("Street"));
                }
                if (add.has("ZIP")) {
                    mCloudAddress.append(add.getString("ZIP"));
                }
                if (add.has("Country")) {
                    mCloudAddress.append(add.getString("Country"));
                }

            }
        } catch (JSONException e) {
            try {
                if (object.has("daddresses")) {
                    JSONObject address = object.getJSONObject("daddresses");
                    mCloudAddress.append(address.getString("_$!<Work>!$_"));
                }
            } catch (JSONException e1) {
                e1.printStackTrace();
            }
        }
        Log.i("cloud_contact_data", object.toString());

        // 性别
        if (mCloudContactSex == 0) {
            mIvContactSex.setVisibility(View.GONE);
        } else if (mCloudContactSex == 1) {
            mIvContactSex.setVisibility(View.VISIBLE);
            mIvContactSex.setImageResource(R.drawable.sex_man);
        } else if (mCloudContactSex == 2) {
            mIvContactSex.setVisibility(View.VISIBLE);
            mIvContactSex.setImageResource(R.drawable.sex_lady);
        }

        // 公司
        if (!StringUtil.isEmpty(mCloudContactCompany)) {
            mTvContactCompany.setText(mCloudContactCompany);
        }

/*部门字段目前没了
        if (!StringUtil.isEmpty(mCloudContactDepartment)) {
            mTvContactDepartment.setVisibility(View.VISIBLE);
            mTvContactDepartment.setText(mCloudContactDepartment);
        } else {
            mTvContactDepartment.setVisibility(View.GONE);
        }
*/

        // 职位
        if (!StringUtil.isEmpty(mCloudContactPosition)) {
            mTvContactPosition.setVisibility(View.VISIBLE);
            mTvContactPosition.setText(mCloudContactPosition);
        } else {
            mTvContactPosition.setVisibility(View.GONE);
        }

        // 邮箱
        if (!StringUtil.isEmpty(mCloudContactEmail)) {
            mTvContactEmail.setText(mCloudContactEmail);
        } else {
            mTvContactEmail.setText("资料未完善");
        }

        if (!StringUtil.isEmpty(mCloudContactName)) {
            mTvContactName.setText(mCloudContactName);
        } else {
            mTvContactName.setText("无名称");
        }

        // 办公地址
        if (!StringUtil.isEmpty(mCloudAddress.toString())) {
            mTvContactAddress.setText(mCloudAddress.toString());
        } else {
            mTvContactAddress.setText("资料未完善");

        }

        // 备注
        if (!StringUtil.isEmpty(mCloudContactNote)) {
            mTvContactNote.setText("  " + mCloudContactNote);
        } else {
            mTvContactNote.setText("暂无个人信息");
        }

        // 状态
        String uid = cloudContact.userId;
        if (!uid.equals("0")) {
            mIvContactStatus.setVisibility(View.VISIBLE);
        } else {
            mIvContactStatus.setVisibility(View.GONE);
        }

        ImageLoaderInterface.imageLoader.displayImage(mCloudImage, mIvContactPhoto, ImageLoaderInterface.optionHeadImage);

        // 电话
        if ("1".equals(mLimitPhone)) {//显示电话号码
            ArrayList<PhoneNumItem> contactPhoneNum = cloudContact.contactPhoneNum;
            if (contactPhoneNum != null && contactPhoneNum.size() > 0) {
                Log.i("cloudContact", contactPhoneNum.size() + "");
                // TODO 判断手机号码的个数，一个显示一个，两个以上只显示两个
//            if (contactPhoneNum.size() == 1) {
                mTvContactPhone.setText(contactPhoneNum.get(0).phoneNum);
                mTvContactPhone.setTextColor(getResources().getColor(R.color.cloud_contact_detail_blue));
                mTvContactPhone.setOnClickListener(this);
//            } else if (contactPhoneNum.size() > 1) {
//                mContentLayout.removeAllViews();
//                for (int i = 0; i < 2; i++) {
//                    View cloudPhoneItem = getCloudPhoneItemView(contactPhoneNum.get(i).label, contactPhoneNum.get(i).phoneNum);
//                    mContentLayout.addView(cloudPhoneItem);
//                    mContentLayout.addView(addLine(Constants.dip2px(this, 15)));
//                }
//            }
            }
        } else {
            mTvContactPhone.setText("限制号码公开");
            mTvContactPhone.setTextColor(getResources().getColor(R.color.cloud_contact_detail_light));
        }

        if ("1".equals(mCalendarPurview)) {//共享管理员按钮可点击，即是该日程表管理员
            mTvSchedule.setTextColor(getResources().getColor(R.color.cloud_contact_detail_dark));
        } else {
            mTvSchedule.setTextColor(getResources().getColor(R.color.schedule_unclick_text));
        }


        mDialog.dismiss();
    }


    private void showCallDialog() {
        mDialogUtil.titleOneDialog(mTvContactPhone.getText().toString().trim(), "发短信", "打电话");
        mDialogUtil.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {

            @Override
            public void onConfirmClick(Dialog lDialog) {
                CommonCodeUtil.launchSendMessage(CloudContactDetailActivity.this, mTvContactPhone.getText().toString().trim(), null);
                lDialog.dismiss();

            }

            @Override
            public void onCancelClick(Dialog lDialog) {
                CommonCodeUtil.launchCallByNumber(CloudContactDetailActivity.this, mTvContactPhone.getText().toString().trim());
                lDialog.dismiss();
            }
        });

    }

    public void showPopwindow(boolean isShare) {
        View moreView = LayoutInflater.from(this).inflate(R.layout.detail_more_pop_layout, null);
        Button btnEdit = (Button) moreView.findViewById(R.id.detail_more_edit);
        Button btnDelete = (Button) moreView.findViewById(R.id.detail_more_delete);
        Button btnWxShare = (Button) moreView.findViewById(R.id.detail_more_wx_share);
        Button btnDxShare = (Button) moreView.findViewById(R.id.detail_more_share);
        Button btnAuthIn = (Button) moreView.findViewById(R.id.detail_more_auth_in);
        Button btnAuthLook = (Button) moreView.findViewById(R.id.detail_more_auth_look);
        Button btnCancel = (Button) moreView.findViewById(R.id.detail_more_cancel);
        if (isShare) {
            btnWxShare.setVisibility(View.VISIBLE);
            btnDxShare.setVisibility(View.VISIBLE);
            btnDelete.setVisibility(View.GONE);
            btnAuthIn.setVisibility(View.GONE);
            btnAuthLook.setVisibility(View.GONE);
            btnEdit.setVisibility(View.GONE);
        } else {
            btnWxShare.setVisibility(View.GONE);
            btnDxShare.setVisibility(View.GONE);
            if (mAccess == 0) {
                btnAuthIn.setText("不让他看我的人脉圈");
            } else if (mAccess == 1) {
                btnAuthIn.setText("允许他看我的人脉圈");
            }

            if (mShield == 0) {
                btnAuthLook.setText("不看他的人脉圈");
            } else if (mShield == 1) {
                btnAuthLook.setText("看他的人脉圈");
            }
            if (mPreferenceUtil.getString(PreferenceUtil.CLIENT_USEID, "－1").equals(mUserId)) {
                btnAuthIn.setVisibility(View.GONE);
                btnAuthLook.setVisibility(View.GONE);
            }
            if ("0".equals(mUserType) || "1".equals(mUserType)) {
                btnDelete.setVisibility(View.GONE);
                if (!mPreferenceUtil.getString(PreferenceUtil.CLIENT_USEID, "－1").equals(mUserId)) {
                    btnEdit.setVisibility(View.GONE);

                }
            }

        }
        // 编辑联系人
        btnEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(CloudContactDetailActivity.this, EditCloudActivity.class);
                intent.putExtra(EditCloudActivity.CLOUD_EDIT_NAME, mCloudContactName);
                intent.putStringArrayListExtra(EditCloudActivity.CLOUD_EDIT_PHONES, mCloudPhoneNumbers);
                intent.putExtra(AsynHttpClient.KEY_CONTACT_ID, mCloudContactId);
                intent.putExtra(AsynHttpClient.KEY_CURRENT_CONTACT_ID, mCloudCurrentContactId);
                intent.putExtra(EditCloudActivity.CLOUD_EDIT_COMPANY, mCloudContactCompany);
                intent.putExtra(EditCloudActivity.CLOUD_EDIT_POSITION, mCloudContactPosition);
                intent.putExtra(EditCloudActivity.CLOUD_EDIT_EMAIL, mCloudContactEmail);
                intent.putExtra(EditCloudActivity.CLOUD_EDIT_IMAGE, mCloudImage);
                intent.putExtra(EditCloudActivity.CLOUD_EDIT_PHONE, cloudContact.contact_phone);
                intent.putExtra(EditCloudActivity.CLOUD_EDIT_SEX, mCloudContactSex);
//                intent.putExtra(EditCloudActivity.CLOUD_EDIT_DEPARTMENT, mCloudContactDepartment);
                intent.putExtra(EditCloudActivity.CLOUD_EDIT_ADDRESS, mCloudAddress.toString());
                intent.putExtra(EditCloudActivity.CLOUD_EDIT_NOTE, mCloudContactNote);
                intent.putExtra(EditCloudActivity.CLOUD_LIMIT_PHONE, mLimitPhone);
                CloudContactDetailActivity.this.startActivityForResult(intent, Constants.ACTIVITY_REQUEST_EDITCLOUDCONTACT);
                mMoreWindow.dismiss();
            }
        });

        /**
         * 分享联系人
         */
        btnDxShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent shareIntent = new Intent(CloudContactDetailActivity.this, CloudDialerActivity.class);
                // TODO 判断是本地分享还是云端分享，本地分享调用原拨号精灵的代码，云端分享直接把名字电话传过去
                shareIntent.setAction("contact_detail_page_share");
                shareIntent.putExtra(Constants.CONTACT_ID_KEY, 222L);
                shareIntent.putExtra(Constants.CONTACT_NAME_KEY, mCloudContactName);
//                    if (mCloudPhoneNumbers.size() == 1) {
                if (mCloudPhoneNumbers.size() > 0) {
                    shareIntent.putExtra(Constants.CONTACT_PHONE_KEY, "电话：" + mCloudPhoneNumbers.get(0));
//                    } else if (mCloudPhoneNumbers.size() > 1) {
//                        shareIntent.putExtra(Constants.CONTACT_PHONE_KEY, "电话：" + mCloudPhoneNumbers.get(0) + "\n" + "电话：" + mCloudPhoneNumbers.get(1));
                } else {
                    shareIntent.putExtra(Constants.CONTACT_PHONE_KEY, "");
                }
                startActivity(shareIntent);
//                setResult(Constants.ACTIVITY_RESULT_DISPLAYCOMMUNICATION_SHARE, shareIntent);
                mMoreWindow.dismiss();
//                finish();
            }
        });

        btnWxShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String phone = "电话：" + mCloudPhoneNumbers.get(0);
                mShareUtil.shareToWx(null, "姓名：" + mCloudContactName + "\n" + phone, null, 1, null);
                mMoreWindow.dismiss();
            }
        });

        /**
         * 删除联系人
         */
        btnDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                deleteContact();
                mMoreWindow.dismiss();
            }
        });
        btnAuthIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if ("0".equals(mUserId)) {
                    Toast.makeText(CloudContactDetailActivity.this, "对不起，该用户未注册,无法进行以下操作", Toast.LENGTH_LONG).show();
                } else {
                    getAuthAccess(CloudContactDetailActivity.this, mHandler.obtainMessage(MSG_AUTH_ACCESS));
                }
                mMoreWindow.dismiss();
            }
        });
        btnAuthLook.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if ("0".equals(mUserId)) {
                    Toast.makeText(CloudContactDetailActivity.this, "对不起，该用户未注册,无法进行以下操作", Toast.LENGTH_LONG).show();
                } else {
                    getAuthShield(CloudContactDetailActivity.this, mHandler.obtainMessage(MSG_AUTH_SHIELD));
                }
                mMoreWindow.dismiss();
            }
        });
        /**
         * 取消操作
         */
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mMoreWindow.dismiss();
            }
        });

        mMoreWindow = new PopupWindow(this);
        mMoreWindow.setContentView(moreView);
        mMoreWindow.setTouchable(true);
        mMoreWindow.setFocusable(true);
        mMoreWindow.setOutsideTouchable(true);
        mMoreWindow.setBackgroundDrawable(new BitmapDrawable());
        mMoreWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        mMoreWindow.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        mMoreWindow.setAnimationStyle(R.style.bottomStyle);
        mMoreWindow.showAtLocation(mMainLayout, Gravity.BOTTOM, 0, 0);
        mMoreWindow.update();

        moreView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                mMoreWindow.dismiss();
                return false;
            }
        });

    }

    /**
     * 删除联系人
     */
    public void deleteContact() {
        String confirmToDel = getString(R.string.dialog_label_confirm_note);
        String delMsg = getString(R.string.delete_one_contact, mCloudContactName);
        String confirmBtn = getString(R.string.ok);
        String cancelBtn = getString(R.string.cancel);
        mDialogUtil.titleMsgBtnStyle(confirmToDel, delMsg, confirmBtn, cancelBtn);
        mDialogUtil.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {

            @Override
            public void onConfirmClick(Dialog lDialog) {
                lDialog.dismiss();
                mDialog.show();
                removeContact(mCloudContactId, mCloudCurrentContactId, mCloudGroupId);
            }

            @Override
            public void onCancelClick(Dialog lDialog) {
                lDialog.dismiss();
            }
        });

    }

    /**
     * 获取云号码联系人详情
     *
     * @param context
     * @param cloudContactID
     * @param message
     */
    private void getCloudContact(Context context, String cloudContactID, Message message) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID,
                LocalLogin.getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CONTACT_ID, cloudContactID));
        GetCloudContactMsg getCloudContactMsg = new GetCloudContactMsg(context, message);
        getCloudContactMsg.mApi = AsynHttpClient.API_CONTACT_GET;
        getCloudContactMsg.mParams = nvps;
        AsynHttpClient.getInstance(context).execCcHttp(getCloudContactMsg);
    }

    /**
     * 向服务器请求删除云端分组内的人
     *
     * @param contactId
     * @param gid
     */
    private void removeContact(String contactId, String currentId, String gid) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID,
                LocalLogin.getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_DELETE_CONTACT_ID, contactId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CURRENT_CONTACT_ID, currentId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, gid));

        GetMsgHttpReceiver addGroup = new GetMsgHttpReceiver(
                mHandler.obtainMessage(REMOVE_CLOUD_CONTACT));
        addGroup.mApi = AsynHttpClient.API_CONTACT_REMOVE;
        addGroup.mParams = nvps;
        AsynHttpClient.getInstance(this).execCcHttp(addGroup);
    }


    /**
     * 是否禁止某用户进入我的个人空间
     *
     * @param context
     * @param message
     */
    private void getAuthAccess(Context context, Message message) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID,
                LocalLogin.getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SET_USER_ID, mUserId));
        if (mAccess == 0) {
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SET_TYPE, "1"));
        } else {
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SET_TYPE, "0"));
        }
        GetCloudContactAuthMsg getCloudContactAuthMsg = new GetCloudContactAuthMsg(context, message);
        getCloudContactAuthMsg.mApi = AsynHttpClient.API_AUTH_ACCESS;
        getCloudContactAuthMsg.mParams = nvps;
        AsynHttpClient.getInstance(context).execUserHttp(getCloudContactAuthMsg);
    }

    /**
     * 屏蔽某人的动态
     *
     * @param context
     * @param message
     */
    private void getAuthShield(Context context, Message message) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID,
                LocalLogin.getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SET_USER_ID, mUserId));
        if (mShield == 0) {
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SET_TYPE, "1"));
        } else {
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SET_TYPE, "0"));
        }
        GetCloudContactAuthMsg getCloudContactAuthMsg = new GetCloudContactAuthMsg(context, message);
        getCloudContactAuthMsg.mApi = AsynHttpClient.API_AUTH_SHIELD;
        getCloudContactAuthMsg.mParams = nvps;
        AsynHttpClient.getInstance(context).execUserHttp(getCloudContactAuthMsg);
    }

    /**
     * 获取云号码联系人详情
     *
     * @param context
     * @param message
     */
    private void getAuthDetail(Context context, Message message) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID,
                LocalLogin.getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SET_USER_ID, mUserId));
        GetCloudContactAuthMsg getCloudContactAuthMsg = new GetCloudContactAuthMsg(context, message);
        getCloudContactAuthMsg.mApi = AsynHttpClient.API_AUTH_DETAIL;
        getCloudContactAuthMsg.mParams = nvps;
        AsynHttpClient.getInstance(context).execUserHttp(getCloudContactAuthMsg);
    }

    /**
     * 个人空间预览, 用于联系人详情页
     *
     * @param context
     * @param message
     */
    private void getTalkPreView(Context context, Message message) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID,
                LocalLogin.getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_TALK_USER_ID, mUserId));
        GetCloudContactTalkPreViewMsg getCloudContactTalkPreViewMsg = new GetCloudContactTalkPreViewMsg(context, message);
        getCloudContactTalkPreViewMsg.mApi = AsynHttpClient.API_TALK_PREVIEW;
        getCloudContactTalkPreViewMsg.mParams = nvps;
        AsynHttpClient.getInstance(context).execTalkHttp(getCloudContactTalkPreViewMsg);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mShaker != null) {
            mShaker.resume();
        } else {
            mShaker = initShake();
        }
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
        if (mShaker != null) {
            mShaker.pause();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        CloudContactAdapter.opening = true;
        if (mShaker != null) {
            mShaker.pause();
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_cloud_chat_btn:
                if (cloudContact != null) {
                    if (mPreferenceUtil.getString(PreferenceUtil.CLIENT_USEID, "0").equals(cloudContact.userId)) {
                        Toast.makeText(CloudContactDetailActivity.this, "对不起，您不能和自己聊天", Toast.LENGTH_LONG).show();
                    } else {
                        if ("0".equals(cloudContact.userId) || StringUtil.isEmpty(cloudContact.userId)) {
                            Toast.makeText(CloudContactDetailActivity.this, "该用户尚未注册，请邀请他注册后再发聊天消息", Toast.LENGTH_LONG).show();
                        } else {
                            /*addChatGroupContact(cloudContact.userId, mCloudContactId);*/
                            RongIM.getInstance().startPrivateChat(CloudContactDetailActivity.this, mUserId, mCloudContactName);

                        }
                    }

                }
                break;
            case R.id.ll_cloud_contact_btn_back:
                if (mLlNote.getVisibility() == View.VISIBLE) {
                    mLlNote.setVisibility(View.GONE);
                    mSvCloudContact.setVisibility(View.VISIBLE);
                    mLlChatBtn.setVisibility(View.VISIBLE);
                } else {
                    finish();
                }
                break;
            case R.id.ll_cloud_contact_btn_more:
                showPopwindow(false);
                break;
            case R.id.cloud_contact_detail_phone:
                if ("1".equals(mLimitPhone)) {
                    showCallDialog();
                } else {
                    Toast.makeText(this, "号码未公开", Toast.LENGTH_LONG).show();
                }

                break;
            case R.id.rl_contact_detail_person_note:
                mSvCloudContact.setVisibility(View.GONE);
                mLlChatBtn.setVisibility(View.GONE);
                mLlNote.setVisibility(View.VISIBLE);
                break;
            case R.id.cloud_contact_photo:
                ArrayList<String> image = new ArrayList<String>();
                image.add(mCloudImage.split("\\?")[0]);
                Intent intent = new Intent(this, ImagePagerActivity.class);
                intent.putExtra(Constants.IMAGE_ORIGIN, Constants.IMAGE_ORIGIN_URL_ARRAY);
                intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, image);
                startActivity(intent);
                break;
            case R.id.cloud_contact_share:
                showPopwindow(true);
                break;
            case R.id.rl_contact_detail_talk_img:
                if ("0".equals(mUserId)) {
                    Toast.makeText(this, "对不起，该用户未注册，无法进入其个人空间", Toast.LENGTH_LONG).show();
                } else {
                    Intent intent1 = new Intent(CloudContactDetailActivity.this, TalkListActivity.class);
                    intent1.setAction(TalkListActivity.OTHER_PERSONAL_SPACE);
                    intent1.putExtra("set_user_id", mUserId);
                    startActivity(intent1);
                }
                break;
            case R.id.rl_contact_detail_schedule:
                if ("1".equals(mCalendarPurview)) {//是管理员
                    Intent calendar = new Intent(CloudContactDetailActivity.this, ScheduleCalendarActivity.class);
                    calendar.putExtra("userId",mUserId);
                    calendar.putExtra("userName",mCloudContactName);
                    startActivity(calendar);
                    finish();
                } else {
                    Toast.makeText(this, "未获授权，不能查看对方日程表", Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.cloud_contact_ll_help:
                Intent help = new Intent(CloudContactDetailActivity.this, WebViewActivity.class);
                help.putExtra("title", "如何使用联系人详情?");
                help.putExtra("type", 17);
                startActivity(help);
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case Constants.ACTIVITY_REQUEST_EDITCLOUDCONTACT:
                if (resultCode == RESULT_OK) {
                    getCloudContact(CloudContactDetailActivity.this, mCloudContactId + "", mHandler.obtainMessage(GET_CLOUD_CONTACT));
                    mDialog.show();
                }
                break;
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (mLlNote.getVisibility() == View.VISIBLE) {
                    mLlNote.setVisibility(View.GONE);
                    mSvCloudContact.setVisibility(View.VISIBLE);
                    mLlChatBtn.setVisibility(View.VISIBLE);
                } else {
                    finish();
                }
                break;
        }
//        return super.onKeyDown(keyCode, event);
        return true;
    }


    public SendCardShakeListener initShake() {
        SendCardShakeListener shaker = new SendCardShakeListener(this);
        shaker.setOnShakeListener(new SendCardShakeListener.OnShakeListener() {

            public void onShake() {
                if (!StringUtil.isEmpty(mTvContactPhone.getText().toString().trim())) {
                    if ("1".equals(mLimitPhone)) {
                        CommonCodeUtil.launchCallByNumber(CloudContactDetailActivity.this, mTvContactPhone.getText().toString().trim());
                    } else {
                        Toast.makeText(CloudContactDetailActivity.this, "号码未公开", Toast.LENGTH_LONG).show();
                    }

                }
            }
        });
        return shaker;
    }

    private void setAuthIcon() {
        if (mAccess == 0) {
            mIvAuthIn.setVisibility(View.GONE);
        } else if (mAccess == 1) {
            mIvAuthIn.setVisibility(View.VISIBLE);
        }
        if (mShield == 0) {
            mIvAuthLook.setVisibility(View.GONE);
        } else if (mShield == 1) {
            mIvAuthLook.setVisibility(View.VISIBLE);
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mShaker != null) {
            mShaker.pause();
            mShaker = null;
        }
    }
}
